#!/usr/bin/env python
# encoding: utf-8
'''
@author: 王震
@license: 四川凡狼科技有限公司
@contact: 2668985108@qq.com
@file: resources.py
@time: 2022/1/13 9:55 下午
@desc:
'''

from app.msg.tips import *
from app.msg.resp import *
from main import db
from flask import request
from app.public.tool import create_key
from app.public.sqlMethods import existence
from app.model.resources.resources import LabelList, ResourcesLabel, Resources, Appreciate, CollectionWorks
from app.serialize.resourcesObj import ResourcesObj, ResourcesLabelObj, ResourcesWork, ResourceDetails, CollectionObj
from app.public.sqlMethods import t
from sqlalchemy import and_


def create_resources(name) -> dict:
    """
    创建标签列表
    :param name:¬
    :return: dict
    """
    if not name:
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        res = LabelList.query.filter(LabelList.name == name).count()
        if res:
            return response_json(code=tips['existence'], msg=tipsText['existence'])
        _labelList = LabelList()
        _labelList.name = name
        _labelList.id = create_key()
        db.session.add(_labelList)
        db.session.commit()
        return response_json()
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def get_system_resources() -> list:
    """
    获取管理系统标签列表
    :return: list
    """
    try:
        res = LabelList.query.filter().all()
        resources_obj = ResourcesObj(many=True)
        data = resources_obj.dump(res)
        return response_list_json(data=data, page_number=0, page_size=len(data))
    except Exception:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def get_customer_resources() -> list:
    """
    获取客户端标签列表
    :return:
    """
    try:
        res = LabelList.query.filter(LabelList.shoe == 1).all()
        resources_obj = ResourcesObj(many=True)
        data = resources_obj.dump(res)
        return response_list_json(data=data, page_number=0, page_size=len(data))
    except Exception:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def add_resources_title(name) -> dict:
    """
    创建资源类型
    :param name: 名称
    :return: dict
    """
    if not name:
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        res = ResourcesLabel.query.filter(ResourcesLabel.name == name).count()
        if res:
            return response_json(code=tips['existence'], msg=tipsText['existence'])
        _resources_label = ResourcesLabel()
        _resources_label.name = name
        _resources_label.id = create_key()
        db.session.add(_resources_label)
        db.session.commit()
        return response_json()
    except EOFError:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def client_resources_list() -> list:
    """
    客户端获取资源类型列表
    :return: list
    """
    try:
        res = ResourcesLabel.query.filter(ResourcesLabel.shoe == 1).all()
        resources_label_obj = ResourcesLabelObj(many=True)
        data = resources_label_obj.dump(res)
        return response_list_json(data=data, page_number=0, page_size=len(data))
    except EOFError:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def system_resources(page_number, page_size) -> list:
    """
    管理系统获取资源类型列表
    :param page_number:  页码
    :param page_size:  每一页显示的条数
    :return:
    """
    try:
        res = ResourcesLabel.query.filter(ResourcesLabel.shoe == 1).paginate(int(page_number), int(page_size), False)
        item = res.items
        resources_label_obj = ResourcesLabelObj(many=True)
        data = resources_label_obj.dump(item)
        return response_list_json(data=data, page_number=res.page, page_size=res.pages)
    except EOFError:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def edit_resources(data) -> dict:
    """
    编辑资源类型
    :param data:
    :return:
    """
    obj = {"id": '', 'name': ""}
    if existence(obj=data, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        res = ResourcesLabel.query.filter(ResourcesLabel.id == data['id']).first()
        if not res:
            return response_json(code=tips['noResult'], msg=tipsText['noResult'])
        for key in data:
            setattr(res, key, data[key]) if hasattr(res, key) else None
        db.session.commit()
        return response_json()
    except Exception:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def delete_resources(id):
    """
    删除资源类型
    :param id: 标签类型id
    :return:
    """
    if not id:
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        res = ResourcesLabel.query.filter(ResourcesLabel.id == id).delete()
        if not res:
            return response_json(code=tips['noResult'], msg=tipsText['noResult'])
        return response_json()
    except Exception:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def create_resources_works(data) -> dict:
    """
    创建资源作品
    :param data: 资源对象
    :return: dict
    """
    obj = {'name': '', 'resourcesLabelId': ''}
    if existence(obj=data, target=obj):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        resources_type = ResourcesLabel.query.filter(ResourcesLabel.id == data['resourcesLabelId']).count()
        #  创建资源时必须存在资源类型
        if not resources_type:
            return response_json(code=tips['not_exist'], msg=tipsText['not_exist'])
        res = Resources.query.filter(Resources.name == data['name']).count()
        #  不允许重复创建资源作品
        if res:
            return response_json(code=tips['existence'], msg=tipsText['existence'])
        resources = Resources()
        for key in data:
            setattr(resources, key, data[key]) if hasattr(resources, key) and data[key] else None
        resources.star = int(resources.star)
        resources.id = create_key()
        db.session.add(resources)
        db.session.commit()
        return response_json()
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'], msg=tipsText['System_error'])


def get_resources_works(page_number, page_size, id) -> list:
    """
    获取资源列表
    :param page_number: 当前页码
    :param page_size: 每一页显示的数据条数
    :return: list
    """
    res = None
    try:
        if not id:
            res = Resources.query.filter(Resources.shoe == 1).paginate(int(page_number), int(page_size), False)
        else:
            res = Resources.query.filter(and_(Resources.shoe == 1, Resources.resourcesTypeId == id)).paginate(int(page_number), int(page_size), False)
        return get_resources(res=res)
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def resources_system_list(page_number, page_size) -> list:
    """
    获取管理系统资源列表
    :param page_number:当前页码
    :param page_size: 每一页显示的数据条数
    :return:
    """
    try:
        res = Resources.query.filter().paginate(int(page_number), int(page_size), False)
        return get_resources(res=res)
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def get_resources(res) -> list:
    """
    资源列表数据序列化
    :param res: 序列化对象
    :return:
    """
    resources_work = ResourcesWork(many=True)
    item = res.items
    data = resources_work.dump(item)
    resources_type = ResourcesObj()
    for key in data:
        obj = ResourcesLabel.query.filter(ResourcesLabel.id == key['resourcesTypeId']).first()
        obj = resources_type.dump(obj)
        key['resourcesTypeObj'] = obj
    return response_list_json(data=data, page_number=res.page, page_size=res.pages)


def add_fabulous(id) -> dict:
    """
    资源点赞
    :param id: 资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = Appreciate.query.filter(and_(Appreciate.userId == obj['id'], Appreciate.resourcesId == id)).first()
        if res:
            return response_json(code=tips['added'], msg=tipsText['added'])
        appreciate = Appreciate()
        appreciate.id = create_key()
        appreciate.userId = obj['id']
        appreciate.resourcesId = id
        db.session.add(appreciate)
        _resources = Resources.query.filter(Resources.id == id).first()
        _resources.fabulous = _resources.fabulous + 1
        db.session.commit()
        return response_json(msg='true')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def cancel_fabulous(id):
    """
    取消点赞
    :param id: 资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        class_res = Appreciate.query.filter(and_(Appreciate.userId == obj['id'], Appreciate.resourcesId == id))
        res = class_res.first()
        if not res:
            return response_json(code=tips["noResult"], msg=tipsText['noResult'])
        class_res.delete()
        _resources = Resources.query.filter(Resources.id == id).first()
        _resources.fabulous = _resources.fabulous - 1
        db.session.commit()
        return response_json(msg='true')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def query_fabulous(id):
    """
    查看当前用户是否点赞过当前资源
    :param id:  资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = Appreciate.query.filter(and_(Appreciate.userId == obj['id'], Appreciate.resourcesId == id)).first()
        if res:
            return response_json(msg='true')
        return response_json(msg='false')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def add_collection(id):
    """
    添加收藏
    :param id:  资源id
    :return:
    """

    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = CollectionWorks.query.filter(
            and_(CollectionWorks.resourcesId == id, CollectionWorks.userId == obj['id'])).count()
        if res:
            return response_json(code=tips['collection'], msg=tipsText['collection'])
        collection_works = CollectionWorks()
        collection_works.id = create_key()
        collection_works.userId = obj['id']
        collection_works.resourcesId = id
        db.session.add(collection_works)
        _resources = Resources.query.filter(Resources.id == id).first()
        _resources.collection = _resources.collection + 1
        db.session.commit()
        return response_json(msg='true')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def cancel_collection(id):
    """
    取消收藏
    :param id: 资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = CollectionWorks.query.filter(and_(CollectionWorks.resourcesId == id, CollectionWorks.userId == obj['id']))
        _res = res.count()
        if not _res:
            return response_json(code=tips['noResult'], msg=tipsText['noResult'])
        res.delete()
        _resources = Resources.query.filter(Resources.id == id).first()
        _resources.collection = _resources.collection - 1
        db.session.commit()
        return response_json(msg='true')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def query_collection(id) -> dict:
    """
    查询当前资源是否加入收藏
    :param id: 资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = CollectionWorks.query.filter(
            and_(CollectionWorks.resourcesId == id, CollectionWorks.userId == obj['id'])).count()
        if res:
            return response_json(msg="true")
        return response_json(msg='false')
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def get_resource_details(id):
    """
    获取资源详情
    :param id:  资源id
    :return:
    """
    if not id or not len(id):
        return response_json(code=tips['parameter_error'], msg=tipsText['parameter_error'])
    try:
        res = Resources.query.filter(Resources.id == id).first()
        if res:
            resource_details = ResourceDetails()
            data = resource_details.dump(res)
            return response_json(data=data)
        else:
            return response_json(data=tips['noResult'], msg=tipsText['noResult'])
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])


def get_collection(page_number, page_size):
    """
    获取个人收藏
    :param page_number: 当前页码
    :param page_size: 每一页显示的数据条数
    :return:
    """
    token = request.headers['token']
    obj = t.loads(token)
    try:
        res = CollectionWorks.query.filter(CollectionWorks.userId == obj['id']).paginate(int(page_number),
                                                                                         int(page_size), False)
        item = res.items
        collection_obj = CollectionObj(many=True)
        data = collection_obj.dump(item)
        for key in data:
            resources_work = ResourcesWork()
            _res = Resources.query.filter(Resources.id == key['resourcesId']).first()
            data = resources_work.dump(_res)
        return response_list_json(data=data, page_number=res.page, page_size=res.pages)
    except Exception as e:
        db.session.rollback()
        return response_json(code=tips['System_error'] + e, msg=tipsText['System_error'])
